package com.demo.util.excel.builders;

import com.demo.util.DownloadUtil;
import com.demo.util.excel.utils.ExcelStyleUtil;
import com.demo.util.excel.utils.ExportExcelUtil;
import com.demo.util.excel.beans.ExcelColumnVO;
import lombok.Cleanup;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class ExportExcelBuilder<T> {

    private final XSSFWorkbook workbook;

    private final Map<String, XSSFCellStyle> styleMap = new HashMap<>();

    public ExportExcelBuilder(@NotNull XSSFWorkbook workbook) {
        this.workbook = workbook;
        styleMap.put("headerStyle", ExcelStyleUtil.getHeaderStyle(workbook));
        styleMap.put("cellStyle", ExcelStyleUtil.getCellStyle(workbook));
    }

    public ExportExcelBuilder<T> addStyle(ExcelStyleBuilder excelStyle) {
        styleMap.putAll(excelStyle.done(workbook));
        return this;
    }

    public ExportExcelBuilder<T> addSheet(@NotNull String sheetName, List<ExcelColumnVO<T>> columns, List<T> data) {
        ExportExcelUtil.addSheet(workbook, sheetName, styleMap, null, columns, data);
        return this;
    }

    public ExportExcelBuilder<T> addSheet(@NotNull String sheetName, Function<T, String> rowCellStyle, List<ExcelColumnVO<T>> columns, List<T> data) {
        ExportExcelUtil.addSheet(workbook, sheetName, styleMap, rowCellStyle, columns, data);
        return this;
    }

    public void save(@NotNull String filePath) throws IOException {
        File file = new File(filePath);
        @Cleanup
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        workbook.write(fileOutputStream);
    }

    public void download(@NotNull HttpServletResponse response, @NotNull String fileName) throws IOException {
        DownloadUtil.setDownLoadFilename(response, fileName);
        @Cleanup
        OutputStream outputstream = response.getOutputStream();
        workbook.write(outputstream);
    }
}